package web.base.system.provider;

import blue.core.common.Page;
import blue.validation.ValidationUtil;
import blue.validation.group.SaveModel;
import blue.validation.group.UpdateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import web.base.system.facade.RoleFacade;
import web.base.system.message.RoleRequest;
import web.base.system.message.RoleResponse;
import web.base.system.model.Role;
import web.base.system.service.RoleService;
import web.base.system.util.RoleConvertor;
import web.core.util.ErrorCode;

/**
 * @author Jin Zheng
 * @since 1.0 2020-09-02
 */
@Component
public class RoleProvider implements RoleFacade
{
	private RoleService roleService;

	public RoleProvider()
	{
	}

	@Override
	public RoleResponse getId(Integer id)
	{
		if (id == null || id < 1)
			throw ErrorCode.NO_PARAM.newException();

		Role role = roleService.get(id);
		return RoleConvertor.toResponse(role);
	}

	@Override
	public RoleResponse save(RoleRequest request)
	{
		if (request.getId() == null || request.getId() < 1)
		{
			ValidationUtil.valid(request, SaveModel.class);
		}
		else
		{
			ValidationUtil.valid(request, UpdateModel.class);
		}
		Role role = RoleConvertor.toRole(request);
		role = roleService.save(role);
		return RoleConvertor.toResponse(role);
	}

	@Override
	public void deleteId(Integer id)
	{
		if (id == null || id < 1)
			throw ErrorCode.NO_PARAM.newException();

		roleService.delete(id);
	}

	@Override
	public Page list(RoleRequest param, Page page)
	{
		Role role = RoleConvertor.toRole(param);
		page = roleService.list(role, page);
		return RoleConvertor.toResponse(page);
	}

	@Autowired
	public void setRoleService(RoleService roleService)
	{
		this.roleService = roleService;
	}
}
